import os
import json
import folder_dialog as fd
import get_json as gj


settings = {
    # 需要解析的目录
    "dir": "/",
    # 是否读取文件内容
    "read": True,
    # 是否仅获取文件名
    "filename_only": True,
    # 需要获取的文件类型（正则）
    "ext": "\\.(json)$",
}


# path = 'E:\\Project\\Repositories\\cpp\\cpp\\httpserver\\py\\export'
# settings["dir"] = os.path.realpath(path)
# sendmsg = json.dumps(gj.get_json(settings))

# print(sendmsg)


async def handle_ws_msg(jsonStr):
    sendmsg = ""
    code = 0

    try:
        data = json.loads(jsonStr)
        match data["req"]:
            case "handshake":
                sendmsg = "ok"
            case "folder_dialog":
                if "folder" in data["type"]:
                    selected_folder = fd.open_folder_dialog()
                    sendmsg = selected_folder
            case "path":
                match data["type"]:
                    case "abs":
                        sendmsg = os.path.abspath(data["path"])
                    case "go":
                        if not os.path.exists(data["path"]):
                            os.makedirs(data["path"])
                        os.startfile(data["path"])
            case "file":
                match data["type"]:
                    case "jsons":
                        settings["dir"] = os.path.realpath(data["path"])
                        sendmsg = json.dumps(gj.get_json(settings))
            case "save":
                par_path = os.path.realpath(os.path.dirname(data["path"]))
                if not os.path.exists(par_path):
                    os.makedirs(par_path)

                async with open(data["path"], "w") as file:
                    file.write(data["data"])
                # 暂时无法实现异步
                return json.dumps(
                    {"msg": os.path.realpath(data["path"]), "code": 0}
                )

            case _:
                sendmsg = "unknown request"
                code = 1
    except:
        sendmsg = "不合法的数据"
        code = -1

    return json.dumps({"msg": sendmsg, "code": code})
